package com.starry.chat.view;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;

import androidx.annotation.Nullable;

import java.util.ArrayList;
import java.util.List;

/**
 * Package:com.eningqu.aipen.ui.view
 * Author:starr
 * Time:2023/11/8 10:04
 * Description: 
 */
public class LoadingView extends androidx.appcompat.widget.AppCompatTextView {

    float num=4;
    float radius=20;
    Paint paint;

    float[] scales={1,1,1,1};

    List<ValueAnimator> valueAnimators=new ArrayList<>();

    public LoadingView(Context context) {
        super(context);
        init();
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public LoadingView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    void init(){
        paint=new Paint();
        paint.setColor(Color.parseColor("#6769E2"));
        paint.setAntiAlias(true);
        animation();
        this.setMinWidth((int) (12*radius));
        this.setMinHeight((int) (2*radius));
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        float ascent = paint.getFontMetrics().ascent;
        for(int i=0;i<num;++i){
            float x=20+(2*i+1)*(radius);
            float y=radius+(-ascent);
            canvas.drawCircle(x,y,radius*scales[i],paint);
        }
    }

    public void animation(){
        int[] delays=new int[]{120,240,360,480};

        for(int i=0;i<4;++i){
            ValueAnimator scaleAnim=ValueAnimator.ofFloat(1,0.3f,1);
            valueAnimators.add(scaleAnim);
            scaleAnim.setDuration(750);
            scaleAnim.setRepeatCount(-1);
            scaleAnim.setStartDelay(delays[i]);
            int index = i;
            scaleAnim.addUpdateListener(animation -> {
                scales[index]= (float) animation.getAnimatedValue();
                postInvalidate();
            });
            scaleAnim.start();
        }
    }

    public void stopAnimation(){
        for(int i=0;i<valueAnimators.size();++i){
            valueAnimators.get(i).cancel();
        }
    }
}
